<?php

use \Doctrine\Common\Annotations\AnnotationReader;

include_once '../config/DatabaseHandler.php';
include_once 'ReflectUtils.php';
include_once '../config/ClassLoader.php';

class DAO{

	private $reader = null;
	private static $INSTANCE = NULL;
	
	private function __construct(){
		$this->reader = new AnnotationReader();
	}
	
	public static function getInstance(){
		if(self::$INSTANCE == null){
			self::$INSTANCE = new DAO(); 
		}
		
		return self::$INSTANCE;
	}
	
	public function save($objeto,$valores){
		
		$props   = ReflectUtils::getAllproperties(get_class($objeto));
		
		$mapping = array();
		foreach ($props as $prop) {
			$prop_nombre = $prop->getName();
		    $setter = ReflectUtils::setter($prop_nombre);
		    if(isset($valores[$prop_nombre]) and !empty($valores[$prop_nombre])){
		    	$objeto->$setter( $valores[$prop_nombre])	;
		    }else{
		    	$objeto->$setter( 'null');
		    }
		      			$mapping[$prop_nombre] = $this->getColumnName($prop);
		}
		
		
		$db = new DatabaseHandler();
    	$db->connect();
    
	
	    if ($db->insert_update($objeto,$mapping)){
			@mysql_query("COMMIT");
			$db->disconnect();
			return true;
		}
		return false;
	}
	
	public function getColumnName($property){
		$annotation = $this->reader->getPropertyAnnotation($property,'tvsalud\annotations\Column');
		
		if(!empty($annotation)){
			return $annotation->name;
		}
		
		return $property->getName();
	}
	
	
	
}
?>